package com.xtayfjpk.elasticsearch.test.lucene.filter;

import java.io.IOException;

import org.apache.commons.codec.language.Metaphone;
import org.apache.lucene.analysis.TokenFilter;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.analysis.tokenattributes.CharTermAttribute;
import org.apache.lucene.analysis.tokenattributes.TypeAttribute;

public class MetaphoneReplacementFilter extends TokenFilter {
	public static final String METAPHONE = "metaphone";
	private Metaphone metaphoner = new Metaphone();
	private CharTermAttribute termAttr;
	private TypeAttribute typeAttr;
	
	public MetaphoneReplacementFilter(TokenStream input) {
		super(input);
		termAttr = addAttribute(CharTermAttribute.class);
		typeAttr = addAttribute(TypeAttribute.class);
	}

	@Override
	public boolean incrementToken() throws IOException {
		if(!input.incrementToken()) {
			return false;
		}
		String encoded = metaphoner.encode(termAttr.toString());
		termAttr.setEmpty();
		termAttr.append(encoded);
		typeAttr.setType(METAPHONE);
		return true;
	}

	public static void main(String[] args) {
		Metaphone metaphoner = new Metaphone();
		System.out.println(metaphoner.encode("cat"));
	}
}
